extends CharacterBody2D

var MAX_SPEED := 400
var acceleration := 200
var turnspeed := 4

var speed := 0
var forward := 0
var turn := 0

const TANK_ROTATION_OFFSET := PI / 2
var  tank_rotation := 0

@onready var weapon: Sprite2D = %weapon
@onready var body: Node2D = $body

func _input(event: InputEvent) -> void:
	if Input.is_action_pressed("fire"):
		print("weapon's position : %s, mouse's position : %s" %
		[weapon.global_position ,
		 get_viewport().get_mouse_position()])
		print('weapon_rotation : %s, mouse_rotation : %s,2/PI : %s' %
		[weapon.rotation+ TANK_ROTATION_OFFSET,
		((get_viewport().get_mouse_position() - weapon.global_position)*Vector2.DOWN).angle(),
		TANK_ROTATION_OFFSET ])

func _physics_process(delta: float) -> void:
	
	
	var direction := Input.get_vector("move_left","move_right","move_up","move_down")
	
	if direction != Vector2.ZERO:
		tank_rotation = change_tank_rotato_to(direction,delta)

	#body.rotation = move_toward(body.rotation,direction.angle() + PI / 2,5 * delta)
	#
	#if direction != Vector2.ZERO:
		#angular_velocity += direction.x * rotation_speed * delta * sign(direction.y)
	#else:
		#angular_velocity = lerp(angular_velocity, 0.0, turn_resistance * delta)
		#
	##move_toward(body.rotation)
	#body.rotation += angular_velocity * delta
	#velocity = direction.normalized() * SPEED
	#
	var mouse_position := get_viewport().get_mouse_position()
	weapon.rotation = (mouse_position - weapon.global_position).angle() \
		+ tank_rotation + TANK_ROTATION_OFFSET
	
	move_and_slide()
	
func change_tank_rotato_to(direction : Vector2,delta: float)-> float:
	# 获取目标角度
	var target_angle = direction.angle() + TANK_ROTATION_OFFSET

	# 计算当前角度和目标角度之间的差值
	var angle_diff = fmod(target_angle - body.rotation, TAU)

	# 确保角度差值在 -PI 到 PI 之间（选择最短路径）
	if angle_diff > PI:
		angle_diff -= TAU
	elif angle_diff < -PI:
		angle_diff += TAU

	# 确保角度保持在 -PI 到 PI 之间（可选，用于保持角度规范化）
	body.rotation = fmod(body.rotation, TAU)
	if body.rotation > PI:
		body.rotation -= TAU

	# 应用旋转，使用Math.clamp确保旋转速度限制
	
	body.rotation = body.rotation + clamp(angle_diff, -5 * delta, 5 * delta)
	return body.rotation
